<template>
  <div>
    <el-dialog :title="addtitle" :visible="showDialog" @close="close">
      <el-form ref="addDept" :model="formData" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="部门名称">
          <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
        </el-form-item>
        <el-form-item prop="code" label="部门编码">
          <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
        </el-form-item>
        <el-form-item prop="managerId" label="部门负责人">
          <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
            <el-option
              v-for="item in managerList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="introduce" label="部门介绍">
          <el-input v-model="formData.introduce" placeholder="1-100个字符" type="textarea" size="mini" :rows="4" style="width: 80%" />
        </el-form-item>
        <el-form-item>
          <!-- 按钮 -->
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="upData">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog></div>

</template>
<script>
// 引入请求部门的api
import { getDepartment, getManagerList, addDepartment, getOneDepartment, editDepartment } from '@/api/department'
export default {
  name: 'AddDept',
  // 接收父组件数据
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    addid: {
      type: Number,
      default: -1
    },
    addtitle: {
      type: String,
      default: null
    }

  },
  data() {
    return {
      pid: '', // 父级部门的id
      editdata: {},
      formData: {
        code: '', // 部门编码
        introduce: '', // 部门介绍
        managerId: '', // 部门负责人id
        name: '' // 部门名称

      },
      // 负责人数组
      managerList: [],
      // 校验规则
      rules: {
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          {
            min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur'
          },
          {
            trigger: 'blur',
            // 自定义校验模式
            validator: async(rule, value, callback) => {
              // console.log(rule)
              const result = await getDepartment()
              // console.log(result)
              // 判断当前部分是否已经存在
              // findIndex  下标 不等于 -1  存在
              // find   不等于  假   存在
              // some   只要有一个满足条件 都返回true
              // every 每一个都满足条件 才返回true
              if (result.data.some(a => a.code === value && a.pid !== this.pid)) {
                callback(new Error('编码重复'))
                return
              } else {
                callback()
              }
            }
          }
        ], // 部门编码
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' }, {
          min: 1, max: 100, message: '部门介绍的长度为1-100个字符', trigger: 'blur'
        }], // 部门介绍
        managerId: [{ required: true, message: '部门负责人不能为空', trigger: 'change' }],
        // 部门负责人id
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          {
            min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur'
          },
          {
            trigger: 'blur',
            // 自定义校验模式
            validator: async(rule, value, callback) => {
              const result = await getDepartment()
              console.log(this.pid)
              if (result.data.some(a => a.name === value && a.pid !== this.pid)) {
                console.log(1)
                callback(new Error('部门重复'))
                return
              } else {
                callback()
              }
            }
          }]
      }
    }
  },
  watch: {
    async showDialog(newval) {
      // console.log(newval)
      if (newval === false) {
        await this.$refs.addDept.resetFields()
        this.pid = ''
      }
      if (newval === true) {
        if (this.addtitle === '编辑部门') {
          // console.log(this.addid)
          const result = await getOneDepartment(this.addid)
          // console.log(result)
          this.editdata = result.data
          const { code, introduce, managerId, name, pid } = this.editdata
          this.pid = pid
          this.formData = {
            code,
            introduce,
            managerId,
            name
          }
        }
      }
    }

  },
  async created() {
    const result = await getManagerList()
    this.managerList = result.data
  },
  methods: {
    // 通知父组件关闭弹出框
    close() {
      this.$emit('update:showDialog', false)
    },
    // 新增编辑部门更新数据
    async  upData() {
      await this.$refs.addDept.validate()
      if (this.addtitle === '新增部门') {
        await addDepartment({ ...this.formData, pid: this.addid })
        // 通知父组件更新数据
        await this.$emit('updateDepart')
        this.$message.success('新增成功')
        this.close()
      } else if (this.addtitle === '编辑部门') {
        // console.log(1)
        this.editdata.name = this.formData.name
        this.editdata.introduce = this.formData.introduce
        this.editdata.managerId = this.formData.managerId
        this.editdata.code = this.formData.code
        delete this.editdata.managerName
        await editDepartment(this.addid, { ...this.editdata, createTime: new Date() })
        // console.log(result)
        // 通知父组件更新数据
        await this.$emit('updateDepart')
        this.$message.success('修改成功')
        this.close()
      }
    }

  }
}
</script>
